<?php

/**
 *   OPENSHOP 管理中心花名册管理
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: roster.php,v 1.0 2009/06/17 08:36:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');

$exc = new exchange($os->table("roster"), $db, 'roster_id', 'consignee');

/*------------------------------------------------------ */
//-- 期刊列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
	admin_priv();
	
    $smarty->assign('ur_here',      '目录花名册');
    $smarty->assign('action_link',  array('text' => '添加花名单', 'href' => 'roster.php?act=add'));
    $smarty->assign('full_page',    1);
    
    $roster_list = get_rosterlist();

    $smarty->assign('roster_list', $roster_list['roster']);
    $smarty->assign('filter',       $roster_list['filter']);
    $smarty->assign('record_count', $roster_list['record_count']);
    $smarty->assign('page_count',   $roster_list['page_count']);   

    assign_query_info();
    
    $smarty->display('roster_list.tpl');
    
}elseif($_REQUEST['act']=='add' || $_REQUEST['act']=='edit'){	
    	
    $is_add = $_REQUEST['act'] == 'add';
    
    $priv_str = $is_add ? 'add_roster' : 'edit_roster';
	admin_priv($priv_str);
    
    $smarty->assign('form_act', $is_add ? 'insert' : 'update');    
    
    
    /* 初始化、取得优惠活动信息 */
    if ($is_add)
    {
        $roster = array(
            'roster_id'         => 0,
            'consignee'         => '',
            'sex'               => 0, // 0为保密,1为男,2为女
            'birthday'     	    => '0000-00-00',
	        'email'             => '',
	        'office_phone'      => '',        
	        'home_phone'        => '',
	        'country'           => 1,
	        'province'          => 0,
	        'city'              => 0,
	        'district'          => 0,
	        'address'           => '',
	        'zipcode'           => '',
	        'mobile'            => '',
	        'sign_building'     => '',
	        'best_time'         => '',   
        );
    }
    else
    {
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }
        $roster_id = intval($_GET['id']);
        $roster = roster_info($roster_id);
        if (empty($roster))
        {
            sys_msg('您要操作的花名单不存在');
        }
    }
    $roster['sex_list'] = array( 0 =>'保密', 1 => '男', 2 => '女');
    /* 载入地区*/
    $smarty->assign('country_list', get_regions());
    $smarty->assign('province_list', get_regions(1, $roster['country']));
    $smarty->assign('city_list',  get_regions(2, $roster['province']));
    $smarty->assign('district_list',  get_regions(3, $roster['city']));
    $smarty->assign('name_of_region',   array($_CFG['name_of_region_1'], $_CFG['name_of_region_2'], $_CFG['name_of_region_3'], $_CFG['name_of_region_4']));
    $smarty->assign('roster', $roster);
    
    /* 显示模板 */
    if ($is_add)
    {
        $smarty->assign('ur_here', '添加花名单');
    }
    else
    {
        $smarty->assign('ur_here', '编辑花名单');
    }
    $href = 'roster.php?act=list';
    if (!$is_add)
    {
        $href .= '&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => '目录花名册管理'));
            
	assign_query_info();
	
	$smarty->display('roster_info.tpl');	
	
}elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update'){
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert';

    $priv_str = $is_add ? 'add_roster' : 'edit_roster';
	admin_priv($priv_str);
	
    /* 提交值 */
    $roster = array(
        'roster_id'         => intval($_POST['id']),
        'consignee'         => empty($_POST['consignee']) ? '' : trim($_POST['consignee']),
        'sex'               => in_array(intval($_POST['sex']), array(0, 1, 2)) ? $_POST['sex'] : 0,    
        'birthday'          => $_POST['birthdayYear'] . '-' .  $_POST['birthdayMonth'] . '-' . $_POST['birthdayDay'],
        'email'             => empty($_POST['email']) ? '' : trim($_POST['email']),
        'office_phone'      => empty($_POST['office_phone']) ? '' : trim($_POST['office_phone']),        
        'home_phone'        => empty($_POST['home_phone']) ? '' : trim($_POST['home_phone']),
        'country'           => intval($_POST['country']),
        'province'          => intval($_POST['province']),
        'city'              => intval($_POST['city']),
        'district'          => intval($_POST['district']),
        'address'           => empty($_POST['address']) ? '' : trim($_POST['address']),
        'zipcode'           => empty($_POST['zipcode']) ? '' : trim($_POST['zipcode']),
        'mobile'            => empty($_POST['mobile']) ? '' : trim($_POST['mobile']),
        'sign_building'     => empty($_POST['sign_building']) ? '' : trim($_POST['sign_building']),
        'best_time'         => empty($_POST['best_time']) ? '' : trim($_POST['best_time']),   
        'reg_time'          => gmtime()            
    );
    
    /* 保存数据 */
    if ($is_add)
    {
        $db->autoExecute($os->table('roster'), $roster, 'INSERT');
        $roster['roster_id'] = $db->insert_id();
    }
    else
    {
        $db->autoExecute($os->table('roster'), $roster, 'UPDATE', "roster_id = '$roster[roster_id]'");
    }

    /* 记日志 */
    if ($is_add)
    {
        admin_log($roster['consignee'], 'add', 'roster');
    }
    else
    {
        admin_log($roster['consignee'], 'edit', 'roster');
    }

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    if ($is_add)
    {
        $links = array(
            array('href' => 'roster.php?act=add', 'text' => '继续添加花名单'),
            array('href' => 'roster.php?act=list', 'text' => '返回目录花名册列表')
        );
        sys_msg('添加目录花名单', 0, $links);
    }
    else
    {
        $links = array(
            array('href' => 'roster.php?act=list&' . list_link_postfix(), 'text' => '返回目录花名册列表')
        );
        sys_msg('编辑目录花名单', 0, $links);
    }
    
}elseif ($_REQUEST['act'] == 'remove'){
	
    check_authz_json('drop_roster');

    $id = intval($_GET['id']);

    $sql = "SELECT consignee FROM " .$os->table('roster'). " WHERE roster_id = '$id'";
    $roster_consignee = $db->getOne($sql);
    
//    $catalog_send_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('catalog_send'). " WHERE user_type=0 AND user_id='$id'");
//    
//    if($catalog_send_count==0){
	    /* 删除该颜色 */
	    if($exc->drop($id)){
			admin_log($roster_consignee, 'remove', 'roster');	    	
	    }
//    }else{
//    	make_json_error('"'.$roster_consignee .'" 该花名单用户与发行还有关联,您不能删除!');
//    }
    
    $url = 'roster.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;
    
}elseif ($_REQUEST['act'] == 'query'){
	
    $list = get_rosterlist();

    $smarty->assign('roster_list',     $list['roster']);
    $smarty->assign('filter',          $list['filter']);
    $smarty->assign('record_count',    $list['record_count']);
    $smarty->assign('page_count',      $list['page_count']);

    make_json_result($smarty->fetch('roster_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));        
}elseif ($_REQUEST['act'] == 'batch_remove'){
    /* 检查权限 */
    admin_priv('drop_roster');

    if (isset($_POST['checkboxes']))
    {
        $sql = "SELECT consignee FROM " . $os->table('roster') . " WHERE roster_id " . db_create_in($_POST['checkboxes']);
        $col = $db->getCol($sql);
        $consignees = implode(',',addslashes_deep($col));
        $count = count($col);

        $sql = "DELETE FROM " . $os->table('roster') . " WHERE roster_id " . db_create_in($_POST['checkboxes']);
        $col = $db->query($sql);       

        admin_log($consignees, 'batch_remove', 'roster');

        $lnk[] = array('text' => '返回上一页', 'href'=>'roster.php?act=list');
        sys_msg(sprintf('已经成功删除了 %d 个花名单客户。', $count), 0, $lnk);
    }
    else
    {
        $lnk[] = array('text' => '返回上一页', 'href'=>'roster.php?act=list');
        sys_msg('您现在没有需要删除的花名单客户！', 0, $lnk);
    }
}elseif($_REQUEST['act']=='transfer'){
	
	admin_priv('transfer_to_member');
		
	$smarty->assign('form_act','register');
	
	assign_query_info();
	
	$smarty->display('roster_transfer_user.tpl');		
}elseif($_REQUEST['act']=='register'){
	
	/* 检查权限 */
	admin_priv('transfer_to_member');
	
    $username = empty($_POST['username']) ? '' : trim($_POST['username']);
    $nickname = empty($_POST['nickname']) ? $username : trim($_POST['nickname']);
    $password = empty($_POST['password']) ? '' : trim($_POST['password']);
    $email = empty($_POST['email']) ? '' : trim($_POST['email']);
    $sex = empty($_POST['sex']) ? 0 : intval($_POST['sex']);
    $sex = in_array($sex, array(0, 1, 2)) ? $sex : 0;
    $birthday = $_POST['birthdayYear'] . '-' .  $_POST['birthdayMonth'] . '-' . $_POST['birthdayDay'];
    $rank = empty($_POST['user_rank']) ? 0 : intval($_POST['user_rank']);
    $credit_line = empty($_POST['credit_line']) ? 0 : floatval($_POST['credit_line']);

    $users =& init_users();

    if (!$users->add_user($username, $password, $email))
    {
        /* 插入客户数据失败 */
        if ($users->error == ERR_INVALID_USERNAME)
        {
            $msg = '无效的客户名';
        }
        elseif ($users->error == ERR_USERNAME_NOT_ALLOW)
        {
            $msg = '客户名不允许注册';
        }
        elseif ($users->error == ERR_USERNAME_EXISTS)
        {
            $msg = '已经存在一个相同的客户名。';
        }
        elseif ($users->error == ERR_INVALID_EMAIL)
        {
            $msg = '无效的email地址';
        }
        elseif ($users->error == ERR_EMAIL_NOT_ALLOW)
        {
            $msg = '邮件不允许';
        }
        elseif ($users->error == ERR_EMAIL_EXISTS)
        {
            $msg = '该邮件地址已经存在。';
        }
        else
        {
            //die('Error:'.$users->error_msg());
        }
        sys_msg($msg, 1);
    }

    /* 注册送积分 */
    if (!empty($GLOBALS['_CFG']['register_points']))
    {
        log_account_change($_SESSION['user_id'], 0, 0, $GLOBALS['_CFG']['register_points'], $GLOBALS['_CFG']['register_points'], '注册送积分');
    }

    /* 更新客户的其它信息 */
    $other =  array();
    $other['credit_line'] = $credit_line;
    $other['user_rank']  = $rank;
    $other['sex']        = $sex;
    $other['birthday']   = $birthday;
    $other['nick_name'] = $nickname;
    
    foreach ($_POST['other'] as $key=>$val)
    {
        if (intval($key) < 1 & !empty($val))
        {
            $other[$key] = htmlspecialchars(trim($val));
        }
    }
    $db->autoExecute($os->table('users'), $other, 'UPDATE', "user_name = '$username'");

    /* 添加额外用户属性 */
    $sql_id = "SELECT user_id FROM ".$os->table('users')." WHERE user_name = '".$username."'";
    $user_id = $db->getOne($sql_id);
    
    $others = $_POST['other']; 
    if ($others)
    {
        foreach ($others as $key=>$val)
        {
            //删除非法key值
            if (intval($key) > 0 ) {
                    // 插入后台用户添加属性数值
                    if (is_array($val) & !empty($val)) {
                        foreach($val as $val)
                        {
                            $t_value .= $val.' ';
                        }
                        $val = $t_value;
                    }
                    $value = $val;  
                    $sqln = "INSERT INTO " .$GLOBALS['os']->table('user_attribute_value'). " (user_id, attr_id, attr_value)".
                            "VALUES (".$user_id. "," .$key.",'". $value ."')";
                    $db->query($sqln);                   
            }
        }
    }
    
    /* 记录管理员操作 */
    admin_log($_POST['username'], 'add', 'users');

    /* 提示信息 */
    $link[] = array('text' => '返回上一页', 'href'=>'users.php?act=list');
    sys_msg(sprintf('客户账号 %s 已经添加成功。', htmlspecialchars(stripslashes($_POST['username']))), 0, $link);
}elseif ($_REQUEST['act'] == 'edit_email'){
    /* 检查权限 */
    check_authz_json('edit_roster');

    $id = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
    $email = empty($_REQUEST['val']) ? '' : json_str_iconv(trim($_REQUEST['val']));
    
    $sql = "SELECT consignee FROM " . $os->table('roster') . " WHERE roster_id = '$id'";
    $consignee = $db->getOne($sql);	
    
    if (is_email($email))
    {
        if ($exc->is_only('email', $email, $id))
        {
        	$exc->edit("email='$email'", $id);
            admin_log(addslashes($consignee), 'edit', 'roster');
            make_json_result(stripcslashes($email));
        }
        else
        {
            make_json_error('该EMail已经存在');
        }
    }
    else
    {
        make_json_error('更新EMail失败');
    }	
}elseif ($_REQUEST['act'] == 'edit_email'){
    /* 检查权限 */
    check_authz_json('edit_roster');

    $id = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
    $email = empty($_REQUEST['val']) ? '' : json_str_iconv(trim($_REQUEST['val']));
    
    $sql = "SELECT consignee FROM " . $os->table('roster') . " WHERE roster_id = '$id'";
    $consignee = $db->getOne($sql);	
    
    if (is_email($email))
    {
        if ($exc->is_only('email', $email, $id))
        {
        	$exc->edit("email='$email'", $id);
            admin_log(addslashes($consignee), 'edit', 'roster');
            make_json_result(stripcslashes($email));
        }
        else
        {
            make_json_error('该EMail已经存在');
        }
    }
    else
    {
        make_json_error('更新EMail失败');
    }	
}elseif ($_REQUEST['act'] == 'edit_mobile'){
    /* 检查权限 */
    check_authz_json('edit_roster');

    $id = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
    $mobile = empty($_REQUEST['val']) ? '' : json_str_iconv(trim($_REQUEST['val']));
    
    $sql = "SELECT consignee FROM " . $os->table('roster') . " WHERE roster_id = '$id'";
    $consignee = $db->getOne($sql);	
    
    if (!empty($mobile))
    {
        if ($exc->is_only('mobile', $mobile, $id))
        {
        	$exc->edit("mobile='$mobile'", $id);
            admin_log(addslashes($consignee), 'edit', 'roster');
            make_json_result(stripcslashes($mobile));
        }
        else
        {
            make_json_error('该Mobile已经存在');
        }
    }
    else
    {
        make_json_error('更新Mobile失败');
    }	
}

function roster_info($roster_id){
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('roster') .
            " WHERE roster_id = '$roster_id'";
    $row = $GLOBALS['db']->getRow($sql);

    return $row;	
}
?>